package study.lxy.spring.springboot2.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.lxy.spring.springboot2.entity.LoginUser;
import study.lxy.spring.springboot2.mq.sender.LoginSender;
import study.lxy.spring.springboot2.service.LoginService;
import study.lxy.spring.springboot2.utils.RedisUtils;
import study.lxy.spring.springboot2.utils.UUIDUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class LoginServiceImpl implements LoginService {
    private static final Logger logger = LoggerFactory.getLogger(LoginService.class);
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LoginSender sender;
    @Override
    public void setSessionId(LoginUser loginUser) {
        String sessionId = UUIDUtils.getUUID();
        Cookie cookie = new Cookie("SESSION_ID", sessionId);
        logger.info("session_id is {}",cookie.getValue());
        response.addCookie(cookie);
        redisUtils.set("SESSION_ID:" + sessionId,loginUser,900);
        sender.sendLoginLog(loginUser);
    }

    @Override
    public void logOut() {
        String sessionId = getSessionId();
        redisUtils.del("SESSION_ID:" + sessionId);
    }

    private String getSessionId(){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if("SESSION_ID".equals(cookie.getName())){
                return cookie.getValue();
            }
        }
        return null;
    }
}
